clc;
warning('off');
Nr=10;
Ne=2;
M=8;
K=2;
R1=2;
R2=1.5;
e=zeros(1,K);
x_axis=0.0:0.04:0.16;
y_axis=zeros(1,length(x_axis));
y_axis_random_phase=zeros(1,length(x_axis));
y_axis_SDR1=zeros(1,length(x_axis));
y_axis_SDR2=zeros(1,length(x_axis));
num=200;
a=0;
for i=1:num
    sign=1;
    y_axis_SDR_temp1=zeros(1,length(x_axis));
    y_axis_SDR_temp2=zeros(1,length(x_axis));
    disp(i);
    hr=(randn(1,Nr)+1i*randn(1,Nr))/sqrt(2);
    G=(randn(Nr,M)+1i*randn(Nr,M))/sqrt(2);
    Dr=(randn(Ne,Nr,K)+1i*randn(Ne,Nr,K))/sqrt(2);
    for alpha=x_axis
        disp(alpha);
        for k=1:K
            e(1,k)=alpha*sqrt(norm(Dr(:,:,k),2)^2);
        end
        try
%         [ w,F,power ] = Alternate_optimization( hr,G,Dr,e,R,M,Nr,Ne,K );
%         [ power_random ] = random_phase( hr,G,Dr,e,R,M,Nr,Ne,K );
        [ w_SDR,F_SDR,power_SDR1 ] = SDR( hr,G,Dr,e,R1,M,Nr,Ne,K );
        [ w_SDR,F_SDR,power_SDR2 ] = SDR( hr,G,Dr,e,R2,M,Nr,Ne,K );
%         if isnan(power_random)
%             a=a+1;
%             sign=0;
%             disp('false')
%             break;
%         end
        catch
            a=a+1;
            sign=0;
            disp('false')
            break;
        end
        y_axis_SDR_temp1(1,int8(alpha/0.04)+1)=power_SDR1;
        y_axis_SDR_temp2(1,int8(alpha/0.04)+1)=power_SDR2;
    end
   if sign
       y_axis_SDR1=y_axis_SDR1+y_axis_SDR_temp1;
       y_axis_SDR2=y_axis_SDR2+y_axis_SDR_temp2;
   end
end
y_axis_SDR1=y_axis_SDR1/(num-a)
y_axis_SDR1=10*log10(y_axis_SDR1*1000)
y_axis_SDR2=y_axis_SDR2/(num-a)
y_axis_SDR2=10*log10(y_axis_SDR2*1000)
a
%y_axis=y_axis/num;
%plot(x_axis,y_axis,'c->','LineWidth',1.5,'MarkerSize',6);
% hold on;
% plot(x_axis,y_axis_SDR,'r-*','LineWidth',1.5,'MarkerSize',6);
%hold on;
plot(x_axis,y_axis_SDR1,'b-o','LineWidth',1.5,'MarkerSize',6);
hold on;
plot(x_axis,y_axis_SDR2,'r-o','LineWidth',1.5,'MarkerSize',6);
grid on;
xlabel('alpha'); 
ylabel('Worst-case Transmission power (dbm)');
legend('SDP','Random Phase');